import { isUndefined } from "mmb";
import { Next } from "koa";
import { AppCTX } from "../types/koaExtend";

export default async (ctx: AppCTX, next: Next) => {
  const reqUrl = ctx.request.url;
  console.log("pager =>", reqUrl);
  let { pageSize, pageNo, ts } = ctx.query;
  if (isUndefined(pageSize)) {
    pageSize = 10;
  }
  if (isUndefined(pageNo)) {
    pageNo = 1;
  }
  if (isUndefined(ts)) {
    ts = Date.now();
  }

  if (pageNo < 1) {
    ctx.throw(`无效的pageNo:${pageNo}`);
  }

  // 限制C端传入pageSize最大不能超过100
  if (pageSize > 100) {
    pageSize = 100;
  }

  ctx.limit = Number(pageSize);
  ctx.offset = Number((pageNo - 1) * pageSize);
  ctx.ts = Number(ts);
  await next();
};
